<template>
  <div class="log-page">
    <!-- 查询条件 -->

    <el-card class="box-card">
      <h3>查询条件</h3>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="账号：">
          <el-input v-model="searchForm.username" placeholder="请输入账号" clearable />
        </el-form-item>

        <el-form-item label="电话：">
          <el-input style="width: 200px" v-model="searchForm.phone" placeholder="请输入电话" clearable />
        </el-form-item>
          <el-form-item label="角色：">
            <el-select style="width: 180px" v-model="searchForm.roleName" placeholder="请选择角色">
              <el-option v-for="item in roleOptions"
                         :key="item.id"
                         :label="item.roleName"
                         :value="item.roleName"></el-option>
              <!-- 可以添加更多选项 -->
            </el-select>
          </el-form-item>
<!--        </el-select>-->

        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 日志列表 -->
    <el-card class="box-card" style="margin-top: 20px; width: 100%">
      <h3>系统账号列表</h3>
      <div style="margin-bottom: 10px;">
        <el-button type="danger" icon="Delete" @click="onDelete">批量删除</el-button>
        <el-button type="primary" icon="Plus" @click="addAccount">添加</el-button>
      </div>


      <el-table
          :data="logList"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="username" label="姓名" width="120" />
        <el-table-column prop="phone" label="电话" width="180" />
        <el-table-column prop="nickname" label="昵称" width="180" />
        <el-table-column prop="department" label="部门" width="180" />
        <el-table-column prop="role" label="角色" width="180" />
        <el-table-column prop="createTime" label="创建时间" width="180" />

        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button @click="editAccount(scope.row.id)"   type="primary" link size="default">编辑</el-button>
            <el-button @click="removeAccount(scope.row.id)"  type="primary" link size="default">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :total="total"
            layout="total, prev, pager, next, sizes, jumper"
            :page-sizes="[5, 10, 20, 50]"
            background
            @current-change="handlePageChange"
            @size-change="handlePageSizeChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import {ElMessage, ElMessageBox} from 'element-plus'
import {router} from "@/router/index.js";



const searchForm = ref({
  username: '',
  phone: '',
  roleName: '',
})

const logList = ref([]) // 后台返回的日志数据
const total = ref(0) // 总记录数

const pagination = ref({
  currentPage: 1,
  pageSize: 10,
})

// 查询日志列表
const fetchLogList =  () => {
  // try {
  const { currentPage, pageSize } = pagination.value
  axios.post(`/user/getAllSysUser/${currentPage}/${pageSize}`, {

    username: searchForm.value.username|| undefined,
    phone: searchForm.value.phone || undefined,
    role: searchForm.value.roleName || undefined,

  }).then(resp=>{
    logList.value = resp.data.records;
    console.log(logList.value);
    total.value = resp.data.total;
  })
}

// 查询按钮点击
const onSearch = () => {
  pagination.value.currentPage = 1;

  fetchLogList()
}

// 重置查询条件
const onReset = () => {
  searchForm.value.username = ''
  searchForm.value.phone = ''
  searchForm.value.roleName = ''
  onSearch()
}

// 分页变化
const handlePageChange = (newPage) => {
  pagination.value.currentPage = newPage
  fetchLogList()
}
const handlePageSizeChange = (newSize) => {
  pagination.value.pageSize = newSize
  pagination.value.currentPage = 1
  fetchLogList()
}

// 多选项变化
const selectedLogs = ref([])
//
const handleSelectionChange = (selection) => {
  selectedLogs.value = selection
}

// 删除

const onDelete = () => {
  if (selectedLogs.value.length === 0) {
    ElMessage.warning('请选择要删除的日志')
    return
  }
  const ids = selectedLogs.value.map(user => user.id);
  ElMessageBox.confirm(
      '此操作将删除所有选中的账号，是否继续？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        axios.post("/user/batchRemove", ids).then(resp => {
          if (resp.data) {
            ElMessage.success('批量删除成功');
            fetchLogList(); // 重新拉取日志列表
          } else {
            ElMessage.error('批量删除失败');
          }
        }).catch(() => {
          ElMessage.error('请求失败，请稍后重试');
        });
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
}



const removeAccount = (id) => {
  ElMessageBox.confirm(
      '确定删除该账号吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        axios.post(`/user/removeAccount/${id}`,).then(resp => {
          if (resp.data) {
            ElMessage.success('删除成功');
            fetchLogList(); // 重新拉取日志列表
          } else {
            ElMessage.error('删除失败');
          }
        }).catch(() => {
          ElMessage.error('请求失败，请稍后重试');
        });
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
}
const roleOptions = ref()
const getAllRole = () => {
  axios.get("/user/getAllRoles").then(resp => {
    roleOptions.value = resp.data;
  })
}

const editAccount = (id) => {
  router.push("/accountForm/" + id);

}

const addAccount = () => {
  router.push("/accountForm/" + -1);
}
// 初始化加载
onMounted(() => {
  fetchLogList();
  getAllRole();
})
</script>

<style scoped>
.log-page {
  padding: 20px;
}
.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
